<template>
    <div class="_wz_personalSettings">
      <Form ref="userInfoS" :model="alterUserInfoData" label-position="right" :label-width="120" :rules="validateuserInfo">
        <FormItem label="头像">
          <Upload :before-upload="businessLicense" action="" style="color: #2d8cf0;cursor: pointer;">
            <div class="demo-upload-list">
              <img :src="logoUrl" v-if="!!logoUrl"/>
            </div>
          </Upload>
        </FormItem>
        <FormItem label="用户名称" prop="name">
          <i-input v-model="alterUserInfoData.name" placeholder="用户名称" clearable />
        </FormItem>
        <FormItem label="联系电话" prop="mobile">
          <i-input v-model="alterUserInfoData.mobile" placeholder="联系电话" clearable />
        </FormItem>
        <FormItem label="邮箱地址" prop="email">
          <i-input v-model="alterUserInfoData.email" placeholder="邮箱地址" clearable />
        </FormItem>
        <FormItem>
          <Button type="primary" @click="userInfoOk">确定</Button>
        </FormItem>
      </Form>
      <Spin size="large" fix v-if="spinShow"></Spin>
    </div>
</template>
<script>


import {getCurrentInstance,inject,nextTick,reactive, toRefs,toRef,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted, ref,defineComponent,toRaw,watch} from 'vue'
import { useRouter,useRoute } from "vue-router";

import { useMainStore } from '../../store'  //pinia 使用 类似 vuex
import { storeToRefs } from 'pinia'
import {getMenu} from "@/util/getMenu";
//pinia 使用 类似 vuex
const mainStore = useMainStore() //pinia 使用 类似 vuex

//reactive
export default defineComponent({
  name: 'personalSettings',//组件名称
  components: {},//组件引用
  props:[],//是否从登录来 loginSource  true
  setup (props,context) {


    const apiUrl = inject('$apiUrl'); // 变量全局化 后台地址
    const $axios = inject('$axiosInterceptor');// 变量全局化 axios
    const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
    const router = useRouter();//路由跳转使用
    const $common = inject('$common');//自己封装的方法


    //用户数据
    const { userData} = storeToRefs(mainStore)

    const state = reactive({
      spinShow:false,//本页加载
      logoUrl: '',
      alterUserInfoData: {},//修改用户信息
      fileData: {},//图片信息
      validateuserInfo: {
        name: [{required: true, message: '请输入用户名称', trigger: 'blur'},],
        mobile: [
          {required: true, message: '请输入联系电话', trigger: 'blur'},
          {
            validator: (rule, value, callBack) => {
              /^[1][0-9]{10}$/.test(value) ? callBack() : callBack('请输入正确的联系电话')
            }, trigger: 'blur'
          }
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {
            validator: (rule, value, callBack) => {
              /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value) ? callBack() : callBack('请输入正确的邮箱地址')
            }, trigger: 'blur'
          }
        ],
      },
    });


    //头像上传
    const businessLicense = (file)=> {
      let type = file.type.split("/")[0];
      if (type == "image") {//图片
        state.fileData.data = file
        state.logoUrl = window.URL.createObjectURL(file);
      } else {
        $ViewUIPlus.Message.warning({
          content: '请选择jpg、png、jpeg的图片进行上传',
          duration: 3
        });
      }
      return false;
    }



    // 用于获取$refs
    const userInfoS = ref();

    const userInfoOk = ()=> {//个人信息提交
      userInfoS.value.validate(async(valid) => {
        if(valid){

          let formData = new FormData();
          for (let key in state.alterUserInfoData) {
            formData.append(key, state.alterUserInfoData[key]);
          }

          if (!!state.fileData.data) {
            //选择了图片
            formData.append("multipartFile", state.fileData.data);
          }

          state.spinShow = true;
          delete state.alterUserInfoData.logoUrl


          $axios.post(apiUrl.systemLoginUpdateUser,formData).then(async(res) => {
            state.spinShow = false;
            if (!!res) {
              $ViewUIPlus.Message.success('保存成功');
              context.emit('closeFun', true)
              //调用父级方法 更新外侧数据
              // that.updatingUserData(); // 调用父组件的beiChildMethod()方法
            }

          }).catch((err) => {
            console.log("失败", err)
          })

        } else {
          $ViewUIPlus.Message.error('请正确填写表单');
        }
      })
    }




    //初始化数据
    const loadData = ()=>{
      var data = JSON.parse(JSON.stringify(userData.value.userInfo));
      state.alterUserInfoData = data;
      state.logoUrl = !!data.logoUrl ? $axios.imgUrl + data.logoUrl : '';
    }

    // 其他的生命周期
    onBeforeMount (() => {//beforeMount挂载前状态 // console.log("App ===> 相当于 vue2.x 中 beforeMount")

    })
    onMounted (() => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")
      loadData()

    })

    // 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
    onBeforeUpdate (() => {//beforeUpdate 更新前状态 // console.log("App ===> 相当于 vue2.x 中 beforeUpdate")

    })

    onUpdated (() => {//updated 更新完成状态 // console.log("App ===> 相当于 vue2.x 中 updated")

    })

    onBeforeUnmount (() => {//beforeDestroy 销毁前状态  // console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
    })

    onUnmounted (() => {//destroyed 销毁完成状态  // console.log("App ===> 相当于 vue2.x 中 destroyed")
    })

    return {
      ...toRefs(state),
      userInfoS,//ref 使用
      businessLicense,//头像上传
      userInfoOk,//表单提交

    }
  }
})


</script>
<style lang="less">
._wz_personalSettings {
  padding: 10px;
  width: 100%;
  height: 100%;
  background: #fff;

  .demo-upload-list {
    display: inline-block;
    height: 90px;
    width: 90px;
    text-align: center;
    line-height: 80px;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    border: 1px solid rgba(0, 0, 0, .2);
    margin-right: 4px;

    img {
      width: 100%;
      height: 100%;
    }

    .demo-upload-list-cover {
      display: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, .6);

      i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
      }
    }
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }
}
</style>
